package com.icesoft.base.admin.controller;

import com.icesoft.base.admin.entity.SysUser;
import com.icesoft.base.admin.entity.dto.SysUserDTO;
import com.icesoft.base.admin.service.SysUserService;
import com.icesoft.base.manager.entity.system.SysUserLoginRecord;
import com.icesoft.base.manager.helper.AuthUser;
import com.icesoft.base.manager.helper.PageParam;
import com.icesoft.base.manager.helper.PageResp;
import com.icesoft.base.manager.helper.QueryBuilderUtils;
import com.icesoft.base.manager.service.system.SysUserLoginRecordService;
import com.icesoft.core.common.helper.Resp;
import com.icesoft.core.dao.criteria.Page;
import com.icesoft.core.dao.criteria.QueryBuilder;
import com.icesoft.core.web.suppose.safehttp.SafeRequest;
import com.icesoft.core.web.suppose.sms.SmsCodeCheck;
import com.icesoft.core.web.suppose.validation.SafePassword;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.WebUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.UUID;

/**
 * 系统用户个人接口
 */
@RequestMapping("system/userCenter")
@RestController
@AllArgsConstructor
public class SysUserController {
    private SysUserLoginRecordService sysUserLoginRecordService;
    private SysUserService sysUserService;
    private PasswordEncoder passwordEncoder;

    /**
     * 获取个人信息
     */
    @GetMapping("userInfo")
    public Resp<SysUserDTO> userInfo(AuthUser authUser) {
        SysUser currentUser = sysUserService.load(authUser.getId());
        return Resp.success(sysUserService.convertUser(currentUser));
    }

    /**
     * 个人登录记录
     *
     * @param queryParam 实体属性查询条件
     * @param search     筛选查询条件
     * @param pageParam  分页查询条件
     * @return PageResp 分页数据
     */
    @GetMapping("loginRecord")
    public PageResp loginRecord(AuthUser authUser, HttpServletRequest request, SysUserLoginRecord queryParam, String search, PageParam pageParam) {
        int sysUserId = authUser.getId();
        QueryBuilder queryBuilder = QueryBuilder.get("userId", sysUserId);
        QueryBuilderUtils.addRequestParam(queryBuilder, request, queryParam);
        QueryBuilderUtils.addSearchParam(queryBuilder, search, new String[]{"username", "loginIp"});
        Page<SysUserLoginRecord> page = sysUserLoginRecordService.page(queryBuilder, pageParam);
        return new PageResp<>(page);
    }

    /**
     * 用户名重复验证
     */
    @GetMapping("validUsername")
    public Resp<Boolean> validUsername(@RequestParam int id, @RequestParam String username) {
        SysUser user = sysUserService.findByUsername(username);
        if (user != null && user.getId() != id) {
            return Resp.success(false);
        }
        return Resp.success(true);
    }

    /**
     * 手机号名重复验证
     */
    @GetMapping("validPhone")
    public Resp<Boolean> validPhone(@RequestParam int id, @RequestParam String phone) {
        SysUser user = sysUserService.findByPhone(phone);
        if (user != null && user.getId() != id) {
            return Resp.success(false);
        }
        return Resp.success(true);
    }

    /**
     * 个人基础信息修改
     */
    @PostMapping("updateMyBaseInfo")
    public Resp<?> updateBaseInfo(String name, String sex, String headImgUrl, String email, AuthUser authUser) {
        SysUser sysUser = sysUserService.load(authUser.getId());
        if (StringUtils.isNotBlank(name)) {
            sysUser.setName(name);
            authUser.setName(name);
        }
        if (StringUtils.isNotBlank(email)) {
            sysUser.setEmail(email);
        }
        if (StringUtils.isNotBlank(sex)) {
            sysUser.setSex(sex);
        }
        if (StringUtils.isNotBlank(headImgUrl)) {
            sysUser.setHeadImgUrl(headImgUrl);
            authUser.setHeadImgUrl(headImgUrl);
        }
        sysUserService.update(sysUser);
        return new Resp<>();
    }

    private static final String OLD_PHONE_CHECK_TOKEN = "OLD_PHONE_CHECK_TOKEN";

    /**
     * 旧手机号验证
     */
    @PostMapping("checkOldPhone")
    @SmsCodeCheck(phone = "oldPhone")
    public Resp<String> checkOldPhone(HttpServletRequest request, @RequestParam String oldPhone, AuthUser authUser) {
        SysUser sysUser = sysUserService.load(authUser.getId());
        if (!oldPhone.equals(sysUser.getPhone())) {
            return Resp.error("旧手机错误");
        }
        String token = UUID.randomUUID().toString();
        WebUtils.setSessionAttribute(request, OLD_PHONE_CHECK_TOKEN, token);
        return Resp.success(token);
    }

    /**
     * 新手机号绑定
     */
    @PostMapping("updatePhone")
    @SmsCodeCheck()
    public Resp<?> updatePhone(HttpServletRequest request, String token, @RequestParam String phone, AuthUser authUser) {
        SysUser sysUser = sysUserService.load(authUser.getId());
        if (StringUtils.isNotBlank(sysUser.getPhone())) {
            if (StringUtils.isBlank(token)) {
                return Resp.error("缺少参数token");
            }
            String sessionToken = (String) WebUtils.getSessionAttribute(request, OLD_PHONE_CHECK_TOKEN);
            if (!token.equals(sessionToken)) {
                return Resp.error("token错误");
            }
        }
        sysUserService.updatePhone(sysUser, phone);
        return new Resp<>();
    }

    /**
     * 修改本人密码
     */
    @PostMapping(value = "updateMyPassword")
    @SafeRequest
    public Resp<?> updateMyPassword(String oldPassword, @SafePassword String newPassword, AuthUser authUser) {
        SysUser current = sysUserService.load(authUser.getId());
        if (!passwordEncoder.matches(oldPassword, current.getPassword())) {
            return new Resp<>("密码错误");
        }
        current.setPassword(passwordEncoder.encode(newPassword));
        current.setPasswordUpdateTime(new Date());
        sysUserService.save(current);
        return Resp.success();
    }
}
